///////////////////////////////////////////////////////////////////////
// Global Values 
// (which would be macros or statics if JS was not a terrible language)
///////////////////////////////////////////////////////////////////////

// Icons
var break_icon = "icons/palmtree.png";
var work_icon = "icons/briefcase.png";

// Storage keys
var mode_key = "mode";
var break_key = "Break";
var work_key = "Work";
var break_site_key = "sites";
var work_time_key = "work_time";
var break_time_key = "break_time";
var mode_start_time_key = "start_time";
var work_notifications_enabled_key = "work_notifications_enabled";
var break_notifications_enabled_key = "break_notifications_enabled";
var work_notifications_interval_key = "work_notifications_interval";
var break_notifications_interval_key = "break_notifications_interval";
var work_colour_key = "work_colour_key";
var break_colour_key = "break_colour_key";
var work_interval_start_time = "work_interval_start_time_key";
var break_interval_start_time = "break_interval_start_time_key";

// Used to split string containing list of break sites
var separator = "*";

////////////////////////////////////////////////////////////////////
// Functions which have to do with the logic rather than the display
////////////////////////////////////////////////////////////////////

// Get the current active tab url
function get_current_url() {
    current = "";
    kango.browser.tabs.getCurrent(function(tab) {
            current = tab.getUrl();
    });
    return extract_host(current);
}    

// Returns the hostname from an arbitrary url
function extract_host(url) {
	var l = document.createElement("a");
	l.href = url;
	return l.hostname;
}

// Add the given url to the list of break sites
// Switch modes if necessary
function add_break_site(site_url) {
	var break_sites = kango.storage.getItem(break_site_key);
	if (break_sites == null || break_sites == "") {
		break_sites = site_url;
	} else if (break_sites.indexOf(site_url) == -1) {
		break_sites = break_sites + separator + site_url;
	} else {
		return;
	}
	kango.storage.setItem(break_site_key, break_sites);
	change_mode(site_url, false);
}

// Remove the given url from the list of break sites
// Switch modes if necessary
function remove_break_site(site_url) {
	var break_sites = kango.storage.getItem(break_site_key);
	if (break_sites == null || break_sites == "" || break_sites.indexOf(site_url) == -1) {
		return;
	}
	var list_of_sites = break_sites.split(separator)
	var updated_list = new Array();
	for (var i = 0; i < list_of_sites.length; i++) {
		if (site_url != list_of_sites[i]) {
			updated_list.push(list_of_sites[i]);
		}
	}
	kango.storage.setItem(break_site_key, updated_list.join(separator));
	change_mode(site_url, false);
}

// Remove the given url from the list of break sites if it is there.
// Otherwise, add it.
function add_remove_break_site(site_url) {
	var break_sites = kango.storage.getItem(break_site_key);
	if (break_sites == null || break_sites == "") {
		add_break_site(site_url);
		return;
	}
	var list_of_sites = break_sites.split(separator);
	var exists = false;
	for (var i = 0; i < list_of_sites.length; i++) {
		if (site_url == list_of_sites[i]) {
			exists = true;
		}
	}
	if (exists) {
		remove_break_site(site_url);
	} else {
		add_break_site(site_url);
	}
}

// Super important functions for deciding whether to switch modes for a given url. 
// Called whenever user changes tabs or opens new page.
// Also stores timer values and resets the timer if a mode switch occurs.
function change_mode(url, is_tab_change) {

	// Were we in work mode before?
	var was_work_mode = kango.storage.getItem(mode_key) == work_key;
	
	// Are we in work mode now?
	var is_work_mode = true;
	var break_sites = kango.storage.getItem(break_site_key);
	if (break_sites != null && break_sites != "") {
		var list_of_sites = break_sites.split(separator);
		for (var i = 0; i < list_of_sites.length; i++) {
			if (url == list_of_sites[i]) {
				is_work_mode = false;
			}
		}
	}
	
	// Set the icons and mode_key for our current mode
	if (is_work_mode){
		kango.storage.setItem(mode_key, work_key);
		kango.ui.browserButton.setIcon(work_icon);
		kango.ui.browserButton.setTooltipText(work_key);
	} else {
		kango.storage.setItem(mode_key, break_key);
		kango.ui.browserButton.setIcon(break_icon);
		kango.ui.browserButton.setTooltipText(break_key);
	}
			
	// If mode changed, store time data and restart the count
	if (was_work_mode != is_work_mode) {
		var mode_start_time = kango.storage.getItem(mode_start_time_key);
		var time_spent = (new Date).getTime() - mode_start_time;
		if (was_work_mode) {
			var work_time_sum = kango.storage.getItem(work_time_key);
			kango.storage.setItem(work_time_key, time_spent + work_time_sum);
		} else {
			var break_time_sum = kango.storage.getItem(break_time_key);
			kango.storage.setItem(break_time_key, time_spent + break_time_sum);
		}
		kango.storage.setItem(mode_start_time_key, (new Date).getTime());
	
		// If mode has changed, need to restart notification intervals.
		// Disable existing intervals, and start the one relevant to the
		// current mode.
		if (kango.storage.getItem(mode_key) == work_key && kango.storage.getItem(work_notifications_enabled_key)) {
			start_work_notifications();
		} else if (kango.storage.getItem(mode_key) == work_key && !kango.storage.getItem(work_notifications_enabled_key)) {
			remove_notifications();
		} else if (kango.storage.getItem(mode_key) == break_key && kango.storage.getItem(break_notifications_enabled_key)) {
			start_break_notifications();
		} else if (kango.storage.getItem(mode_key) == break_key && !kango.storage.getItem(break_notifications_enabled_key)) {
			remove_notifications();
		}

	} else if (is_tab_change) { // Mode did not change on tab change
		tab_change_time = (new Date).getTime();
		if (kango.storage.getItem(mode_key) == work_key && kango.storage.getItem(work_notifications_enabled_key)) {
			millisec_interval_length = kango.storage.getItem(work_notifications_interval_key) * 60 * 1000;
			remaining_time = millisec_interval_length - (tab_change_time - kango.storage.getItem(work_interval_start_time));
			start_work_notifications_with_offset(remaining_time);
		} else if (kango.storage.getItem(mode_key) == break_key  && kango.storage.getItem(break_notifications_enabled_key) ) {
			millisec_interval_length = kango.storage.getItem(break_notifications_interval_key) * 60 * 1000;
			remaining_time = millisec_interval_length - (tab_change_time - kango.storage.getItem(break_interval_start_time));
			start_break_notifications_with_offset(remaining_time);
		}
	}
		
	send_mode_message();
}

// Function called by event listeners below
function on_change(event){
	change_mode(extract_host(event.url), false);
}
function on_tab_change(event){
	change_mode(extract_host(event.url), true);
}

// Indicate the current mode to the content script so it can change the current
// page appropriately
function send_mode_message() {
	kango.browser.tabs.getCurrent(function(tab) {
		colour = "";
		if (kango.storage.getItem(mode_key) == work_key) {
			colour = kango.storage.getItem(work_colour_key);
		}
		else {
			colour = kango.storage.getItem(break_colour_key);
		}
        tab.dispatchMessage('current_mode', colour);
	});
}

////////////////////////////////////////////////////////
// Code that runs in the background when browser starts
// (like main method)
////////////////////////////////////////////////////////

// Initialize values if they are not set to avoid problems
if (kango.storage.getItem(mode_start_time_key) == null || kango.storage.getItem(mode_start_time_key) == "") {
	kango.storage.setItem(mode_start_time_key, (new Date).getTime());
}
if (kango.storage.getItem(break_time_key) == null || kango.storage.getItem(break_time_key) == "") {
	kango.storage.setItem(break_time_key, 0);
}
if (kango.storage.getItem(work_time_key) == null || kango.storage.getItem(work_time_key) == "") {
	kango.storage.setItem(work_time_key, 0);
}
if (kango.storage.getItem(work_notifications_enabled_key) == null || kango.storage.getItem(work_notifications_enabled_key) == "") {
	kango.storage.setItem(work_notifications_enabled_key, false);
}
if (kango.storage.getItem(break_notifications_enabled_key) == null || kango.storage.getItem(break_notifications_enabled_key) == "") {
	kango.storage.setItem(break_notifications_enabled_key, false);
}

// Set the mode so it isn't null (it will be flipped appropriately on page load)
if (kango.storage.getItem(mode_key) == null || kango.storage.getItem(mode_key) == "") {
	kango.storage.setItem(mode_key, work_key);
}

// Add event listeners
kango.browser.addEventListener(kango.browser.event.TAB_CREATED, on_change);
kango.browser.addEventListener(kango.browser.event.BEFORE_NAVIGATE, on_change);
kango.browser.addEventListener(kango.browser.event.DOCUMENT_COMPLETE, on_change);
kango.browser.addEventListener(kango.browser.event.TAB_CHANGED, on_tab_change);
kango.browser.addEventListener(kango.browser.event.TAB_REMOVED, on_change);

// Add listener for providing mode to content pages
kango.addMessageListener('get_mode', function(event) { send_mode_message() });

// Add listener for providing notifications to content pages
//kango.addMessageListener('show_work_notification', function(event) {
//});
//var myWindow = window.open('work_notify.html','online_manager_work_notification','height=300,width=300');
//kango.addMessageListener('show_break_notification', function(event) {
//});

// hack to check that this script is not running for a
// newly opened notification...
if (window.name.indexOf("OnlinenTimenManager") == -1) {

	// If reopened browser, restore notification settings which existed
	if (kango.storage.getItem(work_notifications_enabled_key) && kango.storage.getItem(mode_key) == work_key) {
		start_work_notifications();
	}
	else if (kango.storage.getItem(break_notifications_enabled_key) && kango.storage.getItem(mode_key) == break_key) {
		start_break_notifications();
	}

	// Make sure the correct mode is set when browser opens
	change_mode(get_current_url(), false);

}

////////////////////////////////////////////////////////////
// Functions which have to do with the display (popup.html)
////////////////////////////////////////////////////////////

// Switches the report between visible and invisible
// Also updates the report when it is made visible
function toggle_report() {
	if (document.getElementById("report").style.display == "") {
		document.getElementById("report").style.display = "none";
		wSmall();
	} else {
		var time_spent_in_current_mode = (new Date).getTime() - kango.storage.getItem(mode_start_time_key);
		var total_work_time = kango.storage.getItem(work_time_key);
		var total_break_time = kango.storage.getItem(break_time_key);
		if (kango.storage.getItem(mode_key) == work_key) {
			total_work_time += time_spent_in_current_mode;
		} else {
			total_break_time += time_spent_in_current_mode;
		}
		document.getElementById("timer").innerHTML = convert(time_spent_in_current_mode);
		document.getElementById("work_time").innerHTML = convert(total_work_time);
		document.getElementById("break_time").innerHTML = convert(total_break_time);
		document.getElementById("report").style.display = "";
		document.getElementById("chartdiv").innerHTML = "";
		document.getElementById("chartdiv").style.display = "";
		wLarge();
		total = total_work_time + total_break_time;
		$.jqplot('chartdiv',  [[['Work', total_work_time/total],['Break', total_break_time/total]]],
			{title: '',
			seriesDefaults: {
				//shadow: true, 
				renderer: jQuery.jqplot.PieRenderer, 
				rendererOptions: { 
					showDataLabels: true, 
					highlightMouseOver: false 
					} 
				},
			legend: { 
				show: true, 
				border: 0, 
				//background: '#eee', 
				rowSpacing: '0px' },
			grid: { background: '#eee', borderWidth: 0, shadow: false } 
			}
		);
	}
}

// Converts the time values (stored as milliseconds) to 00:00:00 format.
function convert(unix_time_millisec) {
	var total_seconds = Math.floor(unix_time_millisec / 1000);
	var total_minutes = Math.floor(total_seconds / 60);
	var hours = Math.floor(total_minutes / 60);
	var minutes = Math.floor(total_minutes - hours * 60);
	var seconds = Math.floor(total_seconds - total_minutes * 60)
	if (hours < 10){
		hours = "0" + hours;
	}
	if (minutes < 10){
		minutes = "0" + minutes;
	}
	if (seconds < 10){
		seconds = "0" + seconds;
	}
	return hours + ":" + minutes + ":" + seconds;
}

// Switches the settings between visible and invisible
// User is also shown the latest settings when they are made visible
function toggle_settings() {
	if (document.getElementById("settings").style.display == "") {
		document.getElementById("settings").style.display = "none";
		wSmall();
	} else {
		document.getElementById("settings").style.display = "";
		wLarge();
		if (kango.storage.getItem(work_notifications_enabled_key)) {
			document.getElementById("work_notifications").style.display = "";
			document.getElementById("work_checkbox").checked = true;
			interval = kango.storage.getItem(work_notifications_interval_key);
			if (interval != null && interval > 0) {
				document.getElementById("work_notifications_interval").value = interval;
			}
		} else {
			document.getElementById("work_checkbox").checked = false;
		}
		if (kango.storage.getItem(break_notifications_enabled_key)) {
			document.getElementById("break_notifications").style.display = "";
			document.getElementById("break_checkbox").checked = true;
			interval = kango.storage.getItem(break_notifications_interval_key);
			if (interval != null && interval > 0) {
				document.getElementById("break_notifications_interval").value = interval;
			}
		} else {
			document.getElementById("break_checkbox").checked = false;
		}
		
		var curr_break_colour = kango.storage.getItem(break_colour_key);
		if (curr_break_colour != null && curr_break_colour != "" ) {
			document.getElementById("break_border").style.display = "";
			document.getElementById("break_border_checkbox").checked = true;
			document.getElementById("break_border_colour").value = curr_break_colour;
		} else {
			document.getElementById("break_border_checkbox").checked = false;
		}
		
		var curr_work_colour = kango.storage.getItem(work_colour_key);
		if (curr_work_colour != null && curr_work_colour != "" ) {
			document.getElementById("work_border").style.display = "";
			document.getElementById("work_border_checkbox").checked = true;
			document.getElementById("work_border_colour").value = curr_work_colour;
		} else {
			document.getElementById("work_border_checkbox").checked = false;
		}
		
		show_list_of_break_sites();
	}
}

// Display a list of checkboxes which can be toggled to add/remove
// from the current list of break sites.
// Done dynamically, since don't actually know how many break
// sites there will be in advance.
function show_list_of_break_sites() {
	var html = "";
	var break_sites = kango.storage.getItem(break_site_key);
	if (break_sites == null || break_sites == "") {
		document.getElementById("list_of_break_sites").innerHTML = "";
		return;
	}
	var list_of_sites = break_sites.split(separator);
	if (list_of_sites.length > 0) {
		html += '<label data-tooltip class="has-tip tip-top" title="Your current list of sites that you have tagged as break sites. Uncheck them to untag them as a break site." for="work_checkbox">List of Break Sites:</label>';
	}
	for (var i = 0; i < list_of_sites.length; i++) {
		url = list_of_sites[i];
		html += '<input type="checkbox" checked="checked" onclick="add_remove_break_site(';
		html += "\'";
		html += url;
		html += "\'";
		html += ')"> ';
		html += url;
		html += "<br>";
	}
	document.getElementById("list_of_break_sites").innerHTML = html;
}

// Avoid having settings and report visible at the same time
function close_report_if_open() {
	document.getElementById("report").style.display = "none";
}
function close_settings_if_open() {
	document.getElementById("settings").style.display = "none";
}

// Enable/disable work notifications
function toggle_work_notifications(){
	work_was_enabled = kango.storage.getItem(work_notifications_enabled_key);
	prev_work_interval = kango.storage.getItem(work_notifications_interval_key);
	if (document.getElementById("work_notifications").style.display == "") {
		// Disable
		kango.storage.setItem(work_notifications_enabled_key, false);
		document.getElementById("work_notifications").style.display = "none";
		remove_notifications();
	} else {
		// Enable
		kango.storage.setItem(work_notifications_enabled_key, true);
		document.getElementById("work_notifications").style.display = "";
		set_work_notifications(work_was_enabled, prev_work_interval);
	}
}

// Enable/disable break notifications
function toggle_break_notifications(){
	break_was_enabled = kango.storage.getItem(break_notifications_enabled_key);
	prev_break_interval = kango.storage.getItem(break_notifications_interval_key);
	if (document.getElementById("break_notifications").style.display == "") {
		// Disable
		kango.storage.setItem(break_notifications_enabled_key, false);
		document.getElementById("break_notifications").style.display = "none";
		remove_notifications();
	} else {
		// Enable
		kango.storage.setItem(break_notifications_enabled_key, true);
		document.getElementById("break_notifications").style.display = "";
		set_break_notifications(break_was_enabled, prev_break_interval);
	}
}

// Set work notifications
function set_work_notifications(work_was_enabled, prev_work_interval){
	element = document.getElementById("work_notifications_interval");
	value = element.options[element.selectedIndex].value;
	kango.storage.setItem(work_notifications_interval_key, value);
	work_is_enabled = kango.storage.getItem(work_notifications_enabled_key);
	cur_work_interval = kango.storage.getItem(work_notifications_interval_key);
	if (kango.storage.getItem(mode_key) == work_key) {
		if (!work_was_enabled && work_is_enabled) {
			start_work_notifications();
		} else if (!work_is_enabled && work_was_enabled) {
			remove_notifications();
		} else if (work_is_enabled && cur_work_interval != prev_work_interval) {
			start_work_notifications();
		}
	}
}

// Set break notifications
function set_break_notifications(break_was_enabled, prev_break_interval){
	element = document.getElementById("break_notifications_interval");
	value = element.options[element.selectedIndex].value;
	kango.storage.setItem(break_notifications_interval_key, value);
	break_is_enabled = kango.storage.getItem(break_notifications_enabled_key);
	cur_break_interval = kango.storage.getItem(break_notifications_interval_key);
	if (kango.storage.getItem(mode_key) == break_key) {
		if (!break_was_enabled && break_is_enabled) {
			start_break_notifications();
		} else if (!break_is_enabled && break_was_enabled) {
			remove_notifications();
		} else if (break_is_enabled && cur_break_interval != prev_break_interval) {
			start_break_notifications();
		}
	}
}

// Cancel all notifications
function remove_notifications(){
	kango.browser.tabs.getAll(function(tabs) {
        for	(var i = 0; i < tabs.length; i++) {
            tabs[i].dispatchMessage('disable_notifications');
        }
	});
}

// Start work notifications
function start_work_notifications(){
	remove_notifications();
	interval = kango.storage.getItem(work_notifications_interval_key);
	kango.browser.tabs.getCurrent(function(tab) {
        tab.dispatchMessage('enable_work_notifications', interval);
	});
	kango.storage.setItem(work_interval_start_time, (new Date).getTime());
}

// Start break notifications
function start_break_notifications(){
	remove_notifications();
	interval = kango.storage.getItem(break_notifications_interval_key);
	kango.browser.tabs.getCurrent(function(tab) {
        tab.dispatchMessage('enable_break_notifications', interval);
	});
	kango.storage.setItem(break_interval_start_time, (new Date).getTime());
}

// Start work notifications with offset
function start_work_notifications_with_offset(offset){
	remove_notifications();
	setTimeout(function() {
		if (kango.storage.getItem(mode_key) == work_key && kango.storage.getItem(work_notifications_enabled_key) ) {
			start_work_notifications();
			kango.browser.tabs.getCurrent(function(tab) {
				tab.dispatchMessage('display_work_notification');
			});
		}
	}, offset);
}

// Start work notifications with offset
function start_break_notifications_with_offset(offset){
	remove_notifications();
	setTimeout(function() {
		if (kango.storage.getItem(mode_key) == break_key && kango.storage.getItem(break_notifications_enabled_key) ) {
			start_break_notifications();
			kango.browser.tabs.getCurrent(function(tab) {
				tab.dispatchMessage('display_break_notification');
			});
		}
	}, offset);
}

// Colour of browser pages
// Enable/disable colours
function toggle_work_border(){
	if (document.getElementById("work_border").style.display == "") {
		// Disable
		kango.storage.setItem(work_colour_key, "");
		document.getElementById("work_border").style.display = "none";
		send_mode_message();
	} else {
		// Enable
		document.getElementById("work_border").style.display = "";
		set_work_border();
	}
}
function toggle_break_border(){
	if (document.getElementById("break_border").style.display == "") {
		// Disable
		kango.storage.setItem(break_colour_key, "");
		document.getElementById("break_border").style.display = "none";
		send_mode_message();
	} else {
		// Enable
		document.getElementById("break_border").style.display = "";
		set_break_border();
	}
}

// Set work border
function set_work_border(){
	element = document.getElementById("work_border_colour");
	value = element.options[element.selectedIndex].value;
	kango.storage.setItem(work_colour_key, value);
	send_mode_message();
}

// Set break border
function set_break_border(){
	element = document.getElementById("break_border_colour");
	value = element.options[element.selectedIndex].value;
	kango.storage.setItem(break_colour_key, value);
	send_mode_message();
}

// Make pop-up extra large (for toggle settings)
function wXLarge() {
    var x = window.screenX;
    var y = window.screenY;
    var w = window.outerWidth;
    window.resizeTo(w, 400); 
    window.moveTo(x, y);
}

// Make pop-up large (for toggle report)
function wLarge() {
    var x = window.screenX;
    var y = window.screenY;
    var w = window.outerWidth;
    window.resizeTo(w, 350); 
    window.moveTo(x, y);
}

// Make pop-up small (for toggle add/remove)
function wSmall() {
    var x = window.screenX;
    var y = window.screenY;
    var w = window.outerWidth;
    window.resizeTo(w, 82); 
    window.moveTo(x, y);
}